﻿using JinYuan.ControlCenters;
using JinYuan.ControlLib;
using JinYuan.Helper;
using JinYuan.Models;
using JinYuan.VirtualDataLibrary;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Text;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace LargeSquareOne
{
    public partial class FrmMain : Form
    {

        //实时更新的定时器
        private System.Windows.Forms.Timer updateTimer;
        public FrmMain()
        {
            InitializeComponent();

            #region 字体加载
            // 加载字体文件
            font.AddFontFile(Environment.CurrentDirectory + "\\Assts\\Fonts\\FZY4JW.ttf");
            //定义成新的字体对象
            FontFamily myFontFamily = new FontFamily(font.Families[0].Name, font);
            myFont = new Font(myFontFamily, 21, System.Drawing.FontStyle.Regular);
            lbl_TitleBar.Font = myFont;
            // 设置背景图片
            //this._backgroundImage = Image.FromFile(System.Windows.Forms.Application.StartupPath + "\\Assts\\Image\\BackGround.png");
            #endregion

            #region 添加工具栏
            naviButton2s.Add(this.nav_Monitor);
            naviButton2s.Add(this.nav_DataMonitor);
            naviButton2s.Add(this.nav_CPK);
            naviButton2s.Add(this.nav_AlarmLog);
            naviButton2s.Add(this.nav_HistotryData);
            naviButton2s.Add(this.nav_SetSystem);
            naviButton2s.Add(this.nav_System);
            naviButton2s.Add(this.nav_User);
            #endregion

            this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            this.SetStyle(ControlStyles.DoubleBuffer, true);
            this.SetStyle(ControlStyles.ResizeRedraw, true);
            this.SetStyle(ControlStyles.Selectable, true);
            this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
            this.SetStyle(ControlStyles.UserPaint, true);

            storeTimer = new System.Timers.Timer();
            storeTimer.Interval = 1000;
            storeTimer.AutoReset = true;
            storeTimer.Elapsed += StoreTimer_Elapsed;
            //开启定时器
            storeTimer.Start();

            updateTimer = new System.Windows.Forms.Timer();
            updateTimer.Interval = 200;
            updateTimer.Tick += UpdateTimer_Tick;
            updateTimer.Start();

            CommonMethods.listener.ScanerEvent += Listener_ScanerEvent;
            CommonMethods.listener.Start();



            this.Load += FrmMain_Load;
            this.FormClosing += FrmMain_FormClosing;

        }

        //加载字体
        private PrivateFontCollection font = new PrivateFontCollection();
        Font myFont = null;
        private Image _backgroundImage;

        //定时存储定时器
        private System.Timers.Timer storeTimer;
        /// <summary>
        /// 时间更新委托
        /// </summary>
        /// <param name="time"></param>
        public delegate void ShowTimeHandler(DateTime time);

        //当前页面索引
        private int CurrentIndex = 0;
        private List<NaviButton2> naviButton2s = new List<NaviButton2>();

        /// <summary>
        /// 全局钩子
        /// </summary>


        private void FrmMain_Load(object sender, EventArgs e)
        {

            InitReadInI();
            UserTimeOut(30);

            ControlCenter controlCenter = ControlCenter.Instance;

            //1.设置登录用户
            this.lbl_LoginLevel.Text = CommonMethods.currentAdmin?.LoginLevel;
            this.lbl_LoginName.Text = CommonMethods.currentAdmin?.LoginName;

            //2.打开日志报警窗体
            CommonNaviButton_Click(this.nav_AlarmLog, null);
            //2.打开图表窗体
            CommonNaviButton_Click(this.nav_Monitor, null);
            //打开集中监控窗体
            CommonNaviButton_Click(this.nav_DataMonitor, null);
            //登录日志
            CommonMethods.AddOPLog(false, $"登录成功，登录用户：{CommonMethods.currentAdmin?.LoginName},权限：{CommonMethods.currentAdmin?.LoginLevel}");

            //自动锁屏
            if (CommonMethods.sysConfig.AutoLock)
            {
                //开启监听键盘和鼠标操作
                Application.AddMessageFilter(new MessageFilter());
            }
            //
            if (CommonMethods.sysConfig != null)
            {
                CommonMethods.AddLog(false, "加载系统配置成功");
            }
            else
            {
                CommonMethods.AddLog(true, "加载系统配置失败");
            }
            if (CommonMethods.sysConfig.MesModeSwitching && !CommonMethods.mesConfig.IsLoginMesOK)
            {
                new FrmMsgBoxOutWithAck(2, "当前为MES模式，请登录！", "MES未登录").ShowDialog();
                FrmLoginMes frmLoginMes = new FrmLoginMes();

                frmLoginMes.ShowDialog();
            }
        }


        #region 读取配置文件

        /// <summary>
        /// 读取配置文件
        /// </summary>
        public void InitReadInI()
        {
            CommonMethods.sysConfig.MesModeSwitching = Convert.ToBoolean(IniConfigHelper.ReadIniData("配置信息", "MES/非MES模式切换", "False"));
            CommonMethods.sysConfig.GetMesParam = Convert.ToBoolean(IniConfigHelper.ReadIniData("配置信息", "是否获取MES参数", "False"));
            CommonMethods.mesConfig.IsGet_Server = IniConfigHelper.ReadIniData("配置信息", "是否获取服务器数据", "1") == "1" ? true : false;
            CommonMethods.sysConfig.OKSwitching = Convert.ToBoolean(IniConfigHelper.ReadIniData("配置信息", "强制OK/正常NG模式切换", "False"));
            CommonMethods.mesConfig.IsGet_3C = IniConfigHelper.ReadIniData("配置信息", "是否存储C模块数据", "1") == "1" ? true : false;
            CommonMethods.mesConfig._外观检测条码计数 = Convert.ToInt32(IniConfigHelper.ReadIniData("配置信息", "外观检测条码计数", "false"));

            CommonMethods.mesConfig.siteCode = IniConfigHelper.ReadIniData("MES配置", "工厂代码", "false");
            CommonMethods.mesConfig.lineCode = IniConfigHelper.ReadIniData("MES配置", "产线编号", "false");
            CommonMethods.mesConfig.equipNum = IniConfigHelper.ReadIniData("MES配置", "设备编号", "false");
            CommonMethods.mesConfig.electricMeterNum.Clear();
            string str = IniConfigHelper.ReadIniData("MES配置", "智能电表编号", "1");
            if (str.Contains(','))
            {
                string[] strArray = str.Split(',');
                for (int i = 0; i < strArray.Length; i++)
                {
                    CommonMethods.mesConfig.electricMeterNum.Add(strArray[i]);
                }

            }

            CommonMethods.mesConfig.listAntiDustAirSpeedNum.Clear();
            CommonMethods.mesConfig.AntiDustAirSpeedCount = Convert.ToInt32(IniConfigHelper.ReadIniData("风速仪", "AntiDustAirSpeedCount", "0"));
            for (int i = 0; i < CommonMethods.mesConfig.AntiDustAirSpeedCount; i++)
            {
                CommonMethods.mesConfig.listAntiDustAirSpeedNum.Add(IniConfigHelper.ReadIniData("风速仪", $"AntiDustAirSpeed{i + 1}", "0"));
            }

            CommonMethods.mesConfig.EquStatuasTime = int.Parse(IniConfigHelper.ReadIniData("MES配置", "EquStatuasTime", "0"));
            CommonMethods.ChangeClassTime = IniConfigHelper.ReadIniData("MES配置", "白夜班交替时间", "0");


            CommonMethods.strDeletepath = IniConfigHelper.ReadIniData("MES配置", "MES日志保存路径", "0") + "\\";
            CommonMethods.strAlarmLogspath = IniConfigHelper.ReadIniData("MES配置", "MES日志保存路径", "0") + "\\Logs\\AlarmLogs\\";
            CommonMethods.strMesLogspath = IniConfigHelper.ReadIniData("MES配置", "MES日志保存路径", "0") + "\\Logs\\MesLogs";
            CommonMethods.strSystemLogspath = IniConfigHelper.ReadIniData("MES配置", "MES日志保存路径", "0") + "\\Logs\\SystemLogs";
            CommonMethods.strErrorLogspath = IniConfigHelper.ReadIniData("MES配置", "MES日志保存路径", "0") + "\\Logs\\ErrorLogs";
            CommonMethods.strsqlLogspath = IniConfigHelper.ReadIniData("MES配置", "MES日志保存路径", "0") + "\\Logs\\SqlLogs\\";
            CommonMethods.strWattrMeterpath = IniConfigHelper.ReadIniData("MES配置", "MES日志保存路径", "0") + "\\Logs\\智能电表数据\\";

            CommonMethods.mesConfig.RotueServerIP = IniConfigHelper.ReadIniData("MES配置", "存储服务器IP地址", "192.168.2.108");
            CommonMethods.mesConfig.LoginMesUrl = IniConfigHelper.ReadIniData("MES配置", "员工权限校验", "0");
            CommonMethods.mesConfig.ParamSetpointRequestMesUrl = IniConfigHelper.ReadIniData("MES配置", "设备参数设定值请求", "0");
            CommonMethods.mesConfig.ChangeParamSetValueMesUrl = IniConfigHelper.ReadIniData("MES配置", "设备参数设定值变更", "0");
            CommonMethods.mesConfig.InPutStationMesUrl = IniConfigHelper.ReadIniData("MES配置", "产品进站", "0");
            CommonMethods.mesConfig.EquProcessProcessParamMesUrl = IniConfigHelper.ReadIniData("MES配置", "产品过程加工参数", "0");
            CommonMethods.mesConfig.ResultProcessParamMesUrl = IniConfigHelper.ReadIniData("MES配置", "产品结果加工参数", "0");
            //CommonMethods.mesConfig.OkNgParamMesUrl = IniConfigHelper.ReadIniData("MES配置", "分档参数", "0");
            CommonMethods.mesConfig.OutStationMesUrl = IniConfigHelper.ReadIniData("MES配置", "产品出站", "0");
            CommonMethods.mesConfig.AlarmCurrencyMesUrl = IniConfigHelper.ReadIniData("MES配置", "设备报警", "0");
            CommonMethods.mesConfig.StatusMesUrl = IniConfigHelper.ReadIniData("MES配置", "设备状态", "0");
            CommonMethods.mesConfig.WattrMeterUrl = IniConfigHelper.ReadIniData("MES配置", "能耗", "0");
            CommonMethods.mesConfig.CollectData = IniConfigHelper.ReadIniData("MES配置", "风速仪", "0");
            CommonMethods.mesConfig.GradingMesUrl = IniConfigHelper.ReadIniData("MES配置", "分档参数", "0");

            //CommonMethods.ProdDRFIDNgQty = Convert.ToInt32(IniConfigHelper.ReadIniData("统计计数", "ProdDRFIDNgQty", "0"));
            //CommonMethods.ProdDXNgQty = Convert.ToInt32(IniConfigHelper.ReadIniData("统计计数", "ProdDXNgQty", "0"));
            //CommonMethods.ProdGRFIDNgQty = Convert.ToInt32(IniConfigHelper.ReadIniData("统计计数", "ProdGRFIDNgQty", "0"));
            //CommonMethods.ProdYLZNgQty = Convert.ToInt32(IniConfigHelper.ReadIniData("统计计数", "ProdYLZNgQty", "0"));

        }
        #endregion


        #region 无操作 系统锁屏+切换到主监控界面
        private void UpdateTimer_Tick(object sender, EventArgs e)
        {

            if (CommonMethods.sysConfig.AutoLock)
            {
                CommonMethods.tickCount++;
                if (CommonMethods.tickCount == CommonMethods.sysConfig.LockPeriod * 60 * 1000 / this.updateTimer.Interval)
                {

                    //锁屏
                    LockWorkStation();
                }
            }
            if (CommonMethods.sysConfig.AutoQieHuanM)
            {
                CommonMethods.tickHomeCount++;
                if (CommonMethods.tickHomeCount == CommonMethods.sysConfig.QieHuanMPeriod * 60 * 1000 / this.updateTimer.Interval)
                {
                    //切换集中监控窗体
                    CommonNaviButton_Click(this.nav_Monitor, null);
                }
            }

        }


        [DllImport("user32")]
        public static extern bool LockWorkStation();

        #endregion

        /// <summary>
        /// 刷卡事件
        /// </summary>
        /// <param name="codes"></param>
        private void Listener_ScanerEvent(ScanerHook.ScanerCodes codes)
        {
            //封装对象
            SysAdmin sysAdmin = new SysAdmin()
            {
                LoginUid = codes.Result,
            };

            //调用查询方法
            sysAdmin = CommonMethods.db.Query<SysAdmin>(it => it.LoginUid == sysAdmin.LoginUid);
            if (sysAdmin == null)
            {

                new FrmMsgBoxOutWithAck(3, "登录用户或密码错误！！！", "登录提示").ShowDialog();
                return;
            }
            else
            {
                this.DialogResult = DialogResult.OK;
                CommonMethods.IsLoginOk = true;
                //存储用户对象
                CommonMethods.currentAdmin = sysAdmin;
                //1.设置登录用户
                this.lbl_LoginLevel.Text = CommonMethods.currentAdmin?.LoginLevel;
                this.lbl_LoginName.Text = CommonMethods.currentAdmin?.LoginName;
                //登录日志
                CommonMethods.AddOPLog(false, $"登录成功，登录用户：{CommonMethods.currentAdmin?.LoginName},权限：{CommonMethods.currentAdmin?.LoginLevel}");
            }
        }





        private void StoreTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            #region 时间异步
            DateTime time = DateTime.Now;
            ShowTimeHandler handler = ShowButtonEven_Run;
            IAsyncResult result = handler.BeginInvoke(time, null, handler);
            #endregion
        }

        #region 获取日期/星期，班次信息，更新
        private void ShowButtonEven_Run(DateTime time)
        {
            try
            {
                this.Invoke(new Action(() =>
                {
                    //this.led_StopState.Value = CommonMethods.EMCStatues;

                    this.lbl_DateTime.Text = CurrentTime + " " + week + " " + $"{CommonMethods.strClass}";
                    if (CommonMethods.plcDevice != null)
                    {
                        this.led_PLCState.Value = CommonMethods.plcDevice.IsConnected;
                    }
                    if (CommonMethods.sysConfig.MesModeSwitching && CommonMethods.mesConfig.IsLoginMesOK)//MES
                    {
                        CommonMethods.mesConfig.isUpMes = true;
                        this.led_MESState.Value = true;
                        lblMS.Visible = true;
                        lblMES.Visible = true;
                        lblMES.Text = CommonMethods.mesConfig.mesUserName;
                    }
                    else
                    {
                        CommonMethods.mesConfig.isUpMes = false;
                        lblMS.Visible = false;
                        lblMES.Visible = false;
                        this.led_MESState.Value = false;
                    }
                    if (CommonMethods.sysConfig.SwipeCardMode && !CommonMethods.IsLoginOk)//刷卡模式
                    {
                        lbl_LoginName.Visible = false;
                        lbl_LoginLevel.Text = "未登录";
                    }
                    else
                    {
                        lbl_LoginName.Visible = true;
                    }

                    if (CommonMethods.sysConfig.ScreenCutting)
                    {
                        CommonNaviButton_Click(this.nav_DataMonitor, null);
                        CommonMethods.sysConfig.ScreenCutting = false;
                    }


                    if (CommonMethods.Statues != null && CommonMethods.Statues.Count > 0)
                    {
                        this.led_RunState.Value = CommonMethods.Statues[0];
                        //this.led_StopState.BlinkOn = CommonMethods.Statues[1];
                        this.led_AlarmState.BlinkOn = CommonMethods.Statues[2];
                        this.led_IldeState.BlinkOn = CommonMethods.Statues[3];

                        if (!CommonMethods.Statues[2])
                        {
                            string SlideAlarm = "当前无报警";
                            this.ucRollText1.Text = SlideAlarm;
                            this.ucRollText1.ForeColor = Color.White;
                            CommonMethods.SlideAlarmText = "";
                        }
                        else
                        {
                            this.ucRollText1.Text = CommonMethods.SlideAlarmText;
                            this.ucRollText1.ForeColor = Color.Red;
                        }
                    }
                }));
            }
            catch (Exception ex)
            {
                LoggerHelp.WriteEX(ex);
            }

        }



        private string CurrentTime
        {
            get { return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); }
        }

        private string[] weeks = new string[] { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
        private string week
        {
            get { return weeks[Convert.ToInt32(DateTime.Now.DayOfWeek)]; }
        }

        #endregion

        #region 屏蔽
        //private void DeviceCommunication(Device device)
        //{
        //    while (!cts.IsCancellationRequested)
        //    {
        //        if (device.IsConnected)
        //        {
        //            //通信读取
        //            foreach (var gp in device.GroupList)
        //            {
        //                byte[] data = null;

        //                int reqLength = 0;
        //                if (gp.StoreArea == "输入线圈" || gp.StoreArea == "输出线圈")
        //                {
        //                    switch (gp.StoreArea)
        //                    {
        //                        case "输入线圈":
        //                            //data = CommonMethods.Modbus.ReadBoolArray(gp.Start, gp.Length);
        //                            reqLength = ShortLib.GetByteLengthFromBoolLength(gp.Length);
        //                            break;
        //                        case "输出线圈":
        //                            //data = CommonMethods.Modbus.WriteBoolArray(gp.Start, gp.Length);
        //                            reqLength = ShortLib.GetByteLengthFromBoolLength(gp.Length);
        //                            break;
        //                        default:
        //                            break;
        //                    }

        //                    if (data != null && data.Length == reqLength)
        //                    {
        //                        //变量解析
        //                        foreach (var variable in gp.VarList)
        //                        {
        //                            DataType dataType = (DataType)Enum.Parse((typeof(DataType)), variable.DataType, true);
        //                            int start = variable.Start - gp.Start;

        //                            switch (dataType)
        //                            {
        //                                case DataType.Bool:
        //                                    variable.VarValue = BitLib.GetBitFromByteArray(data, start, variable.OffsetOrLenght);
        //                                    break;
        //                                default:
        //                                    break;

        //                            }
        //                            //处理
        //                            //直接更新
        //                            device.UpdataVariable(variable);
        //                        }
        //                    }
        //                    else
        //                    {
        //                        device.IsConnected = false;
        //                        break;
        //                    }
        //                }
        //                else
        //                {
        //                    switch (gp.StoreArea)
        //                    {
        //                        case "输入寄存器":
        //                            //data = CommonMethods.Modbus.(gp.Start, gp.Length);
        //                            reqLength = gp.Length * 2;
        //                            break;
        //                        case "输出寄存器":
        //                            //data = CommonMethods.Modbus.ReadOutputRegisters(gp.Start, gp.Length);
        //                            reqLength = gp.Length * 2;
        //                            break;
        //                        default:
        //                            break;
        //                    }
        //                    if (data != null && data.Length == reqLength)
        //                    {
        //                        //变量解析

        //                        foreach (var variable in gp.VarList)
        //                        {
        //                            DataType dataType = (DataType)Enum.Parse((typeof(DataType)), variable.DataType, true);
        //                            int start = variable.Start - gp.Start;
        //                            start *= 2;

        //                            switch (dataType)
        //                            {
        //                                case DataType.Bool:
        //                                    variable.VarValue = BitLib.GetBitFrom2BytesArray(data, start,
        //                                        variable.OffsetOrLenght, dataFormat == DataConvertLib.DataFormat.BADC || dataFormat == DataConvertLib.DataFormat.DCBA);
        //                                    break;
        //                                case DataType.Byte:
        //                                    variable.VarValue = ByteLib.GetByteFromByteArray(data,
        //                                        dataFormat == DataConvertLib.DataFormat.BADC || dataFormat == DataConvertLib.DataFormat.DCBA ? start : start + 1);
        //                                    break;
        //                                case DataType.Short:
        //                                    variable.VarValue = ShortLib.GetShortFromByteArray(data, start, dataFormat);
        //                                    break;
        //                                case DataType.Int:
        //                                    variable.VarValue = ShortLib.GetShortFromByteArray(data, start, dataFormat);
        //                                    break;
        //                                case DataType.UInt:
        //                                    variable.VarValue = UIntLib.GetUIntFromByteArray(data, start, dataFormat);
        //                                    break;
        //                                case DataType.Float:
        //                                    variable.VarValue = FloatLib.GetFloatFromByteArray(data, start, dataFormat);
        //                                    break;
        //                                case DataType.Double:
        //                                    variable.VarValue = DoubleLib.GetDoubleFromByteArray(data, start, dataFormat);
        //                                    break;
        //                                case DataType.Long:
        //                                    variable.VarValue = LongLib.GetLongFromByteArray(data, start, dataFormat);
        //                                    break;
        //                                case DataType.ULong:
        //                                    variable.VarValue = ULongLib.GetULongFromByteArray(data, start, dataFormat);
        //                                    break;
        //                                case DataType.String:
        //                                    variable.VarValue = StringLib.GetStringFromByteArrayByEncoding(data, start, variable.OffsetOrLenght,
        //                                        Encoding.ASCII);
        //                                    break;
        //                                case DataType.ByteArray:
        //                                    variable.VarValue = ByteArrayLib.GetByteArrayFromByteArray(data, start, variable.OffsetOrLenght);
        //                                    break;
        //                                case DataType.HexString:
        //                                    variable.VarValue = StringLib.GetHexStringFromByteArray(data, start, variable.OffsetOrLenght);
        //                                    break;
        //                                default:
        //                                    break;
        //                            }

        //                            //处理
        //                            //先做线性转换，再更新

        //                            variable.VarValue = MigrationLib.GetMigrationValue(variable.VarValue, variable.Scale.ToString(),
        //                                variable.Offset.ToString()).Content;

        //                            device.UpdataVariable(variable);
        //                        }
        //                    }
        //                    else
        //                    {
        //                        device.IsConnected = false;
        //                        break;
        //                    }
        //                }
        //            }
        //        }
        //        else
        //        {
        //            //非首次连接，需要延时
        //            if (device.ReConnectSign)
        //            {
        //                CommonMethods.Modbus?.DisConnect();
        //                Thread.Sleep(device.ReConnectTime);
        //            }
        //            //通信连接
        //            CommonMethods.Modbus = new ModbusTCP();

        //            device.IsConnected = CommonMethods.Modbus.Connect(device.IPAddress, device.Port);

        //            if (device.ReConnectSign)
        //            {
        //                CommonMethods.AddLog(device.IsConnected ? false : true, device.IsConnected ? "控制器重连成功" : "控制器重连失败");
        //            }
        //            else
        //            {
        //                CommonMethods.AddLog(device.IsConnected ? false : true, device.IsConnected ? "控制器初次连接成功" : "控制器初次连接失败");
        //                device.ReConnectSign = true;
        //            }

        //        }
        //    }
        //}
        #endregion

        #region 界面操作

        #region 加载背景图像
        //重绘背景放置闪烁
        //protected override void OnPaintBackground(PaintEventArgs e)
        //{
        //    // 使用DrawImage方法绘制背景图片
        //    e.Graphics.DrawImage(_backgroundImage, 0, 0, this.ClientSize.Width, this.ClientSize.Height);
        //}
        #endregion

        #region 减少闪烁
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;
                return cp;
            }
        }


        #endregion

        #region 无边框拖动
        private System.Drawing.Point mPoint;
        private void Panel_MouseDown(object sender, MouseEventArgs e)
        {
            mPoint = new System.Drawing.Point(e.X, e.Y);
        }

        private void Panel_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                this.Location = new System.Drawing.Point(this.Location.X + e.X - mPoint.X, this.Location.Y + e.Y - mPoint.Y);
            }
        }

        #endregion

        #region 左右切换
        private void btn_Left_Click(object sender, EventArgs e)
        {
            CurrentIndex--;
            if (CurrentIndex >= 0)
            {
                CommonNaviButton_Click(naviButton2s[CurrentIndex], null);
            }
            else
            {
                CurrentIndex++;
            }
        }

        private void btn_right_Click(object sender, EventArgs e)
        {
            CurrentIndex++;
            if (CurrentIndex < naviButton2s.Count)
            {
                CommonNaviButton_Click(naviButton2s[CurrentIndex], null);
            }
            else
            {
                CurrentIndex--;
            }
        }
        #endregion

        #region 通用窗体切换
        /// <summary>
        /// 通用窗体切换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CommonNaviButton_Click(object sender, EventArgs e)
        {
            if (sender is NaviButton2 navi)
            {
                if (Enum.IsDefined(typeof(FormNames), navi.TitleName))
                {
                    //拿到导航按钮对应的窗体枚举值
                    FormNames formNames = (FormNames)Enum.Parse(typeof(FormNames), navi.TitleName, true);

                    //用户权限处理
                    switch (formNames)
                    {
                        case FormNames.日志报警:

                            if (CommonMethods.IsLoginOk)
                            {
                                if (!CommonMethods.currentAdmin.SystemLog)
                                {
                                    new FrmMsgBoxOutWithAck(2, "当前登录用户权限不足！", "权限不足").ShowDialog();
                                    return;
                                }
                            }
                            else
                            {
                                new FrmMsgBoxOutWithAck(2, "请先刷卡登录！", "登录系统").ShowDialog();
                                return;
                            }
                            break;
                        case FormNames.数据分析:
                            // new FrmMsgBoxOutWithAck(2, "功能待开发中…………", "品质测量").ShowDialog();
                            //return;
                            if (CommonMethods.IsLoginOk)
                            {
                                if (!CommonMethods.currentAdmin.SystemLog)
                                {
                                    new FrmMsgBoxOutWithAck(2, "当前登录用户权限不足！", "权限不足").ShowDialog();
                                    return;
                                }
                            }
                            else
                            {
                                new FrmMsgBoxOutWithAck(2, "请先刷卡登录！", "登录系统").ShowDialog();
                                return;
                            }
                            //if (!CommonMethods.currentAdmin.CpkData)
                            //{
                            //    new FrmMsgBoxOutWithAck(2, "当前登录用户权限不足！", "权限不足").ShowDialog();
                            //    return;
                            //}
                            break;
                        case FormNames.数据追溯:
                            if (CommonMethods.IsLoginOk)
                            {
                                if (!CommonMethods.currentAdmin.HistoryData)
                                {
                                    new FrmMsgBoxOutWithAck(2, "当前登录用户权限不足！", "权限不足").ShowDialog();
                                    return;
                                }
                            }
                            else
                            {
                                new FrmMsgBoxOutWithAck(2, "请先刷卡登录！", "登录系统").ShowDialog();
                                return;
                            }
                            break;
                        case FormNames.参数设置:
                            if (CommonMethods.IsLoginOk)
                            {
                                if (!CommonMethods.currentAdmin.ParamSet)
                                {
                                    new FrmMsgBoxOutWithAck(2, "当前登录用户权限不足！", "权限不足").ShowDialog();
                                    return;
                                }
                            }
                            else
                            {
                                new FrmMsgBoxOutWithAck(2, "请先刷卡登录！", "登录系统").ShowDialog();
                                return;
                            }
                            break;
                        case FormNames.系统设置:
                            if (CommonMethods.IsLoginOk)
                            {
                                if (!CommonMethods.currentAdmin.UserManage)
                                {
                                    new FrmMsgBoxOutWithAck(2, "当前登录用户权限不足！", "权限不足").ShowDialog();
                                    return;
                                }
                            }
                            else
                            {
                                new FrmMsgBoxOutWithAck(2, "请先刷卡登录！", "登录系统").ShowDialog();
                                return;
                            }
                            break;
                        case FormNames.用户管理:
                            if (CommonMethods.IsLoginOk)
                            {
                                if (!CommonMethods.currentAdmin.SystemLog)
                                {
                                    new FrmMsgBoxOutWithAck(2, "当前登录用户权限不足！", "权限不足").ShowDialog();
                                    return;
                                }
                            }
                            else
                            {
                                new FrmMsgBoxOutWithAck(2, "请先刷卡登录！", "登录系统").ShowDialog();
                                return;
                            }
                            break;
                        default:
                            break;
                    }

                    //窗体切换
                    OpenForm(this.MainPanel, formNames);
                    //设置Title
                    SetTitle(this.lbl_Title, formNames);
                    //设置选中
                    SetNaviButtonSelected(this.TopPanel, navi);
                }
            }
        }

        /// <summary>
        /// 通用打开窗体
        /// </summary>
        /// <param name="mainPanel">容器控件</param>
        /// <param name="formNames">窗体枚举名称</param>
        private void OpenForm(Panel mainPanel, FormNames formNames)
        {
            int total = mainPanel.Controls.Count;
            int closeCount = 0;
            bool isFind = false;

            for (int i = 0; i < total; i++)
            {
                Control ct = mainPanel.Controls[i - closeCount];
                if (ct is Form frm)
                {
                    //如果当前Form是我们需要操作的窗体
                    if (frm.Text == formNames.ToString())
                    {
                        frm.BringToFront();
                        isFind = true;
                        break;
                    }
                    //如果当前Form不是我们需要操作的窗体，然后判断是否为固定窗体，如果不是，则关闭，如果是，则不做处理
                    else if ((FormNames)Enum.Parse(typeof(FormNames), frm.Text, true) >= FormNames.临界窗体)
                    {
                        frm.Close();
                        closeCount++;
                    }
                }
            }

            if (!isFind)
            {
                Form frm = null;

                switch (formNames)
                {
                    case FormNames.集中监控:
                        frm = new FrmMonitor();
                        break;
                    case FormNames.数据监控:
                        frm = new FrmDataMonitor();
                        CommonMethods.AddDataMonitorDelegate += ((FrmDataMonitor)frm).AddDataMonitorLog;//日志记录显示
                        CommonMethods.ShowFeedingDelegate += ((FrmDataMonitor)frm).ShowFeedingData;//上料显示
                        CommonMethods.ShowBlankingDelegate += ((FrmDataMonitor)frm).ShowBankdingData;//下料显示
                        CommonMethods.ChangeParamDelegate += ((FrmDataMonitor)frm).GetLocalParaData;//参数更新
                        break;
                    case FormNames.日志报警:
                        frm = new FrmAlarmLog();
                        //绑定委托
                        CommonMethods.AddLogDelegate += ((FrmAlarmLog)frm).AddLog;//系统日志
                        CommonMethods.AddOPLogDelegate += ((FrmAlarmLog)frm).AddOPLog;//操作日志
                        CommonMethods.AddAlarmDelegate += ((FrmAlarmLog)frm).AddAlarm;//报警日志
                        CommonMethods.ShowAlarmDelegate += ((FrmAlarmLog)frm).ShowAlarm;
                        break;
                    case FormNames.临界窗体:
                        break;
                    case FormNames.数据分析:
                        frm = new FrmCpkCount();
                        break;
                    case FormNames.数据追溯:
                        frm = new FrmHistory();
                        break;
                    case FormNames.参数设置:
                        frm = new FrmRecipe();
                        break;
                    case FormNames.系统设置:
                        frm = new FrmSystemSet(CommonMethods.devPath);
                        break;
                    case FormNames.用户管理:
                        frm = new FrmUserManage();
                        break;
                    default: break;
                }

                if (frm != null)
                {
                    //设置非顶层窗体
                    frm.TopLevel = false;
                    //去除边框
                    frm.FormBorderStyle = FormBorderStyle.None;
                    //填充
                    frm.Dock = DockStyle.Fill;
                    //设置父容器为容器控件
                    frm.Parent = mainPanel;
                    //置前
                    frm.BringToFront();
                    frm.Show();
                }
            }
        }


        /// <summary>
        /// 设置标题内容
        /// </summary>
        /// <param name="label">标题控件</param>
        /// <param name="formNames">窗体枚举名称</param>
        private void SetTitle(Label label, FormNames formNames)
        {
            label.Text = formNames.ToString();
        }

        /// <summary>
        /// 设置导航按钮选中
        /// </summary>
        /// <param name="topPanel">导航按钮的容器</param>
        /// <param name="naviButton">导航按钮</param>
        private void SetNaviButtonSelected(Panel topPanel, NaviButton2 naviButton)
        {
            foreach (var item in topPanel.Controls.OfType<NaviButton2>())
            {
                item.IsSelected = false;
            }
            naviButton.IsSelected = true;
        }
        #endregion

        #region 退出确认
        private void btExit_MouseDown(object sender, MouseEventArgs e)
        {
            this.Close();
        }

        private void btnScale_Click(object sender, EventArgs e)
        {
            this.Visible = false;
        }

        private void FrmMain_SizeChanged(object sender, EventArgs e)
        {
            //当窗体最小化时
            if (!this.Visible)
            {
                this.Visible = false;
                notifyIcon1.Visible = true;
            }
            else
            {
                this.Visible = true;
                notifyIcon1.Visible = true;
            }
        }

        private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                //显示窗体
                this.Visible = true;
                //恢复窗体尺寸状态
                this.WindowState = FormWindowState.Normal;
            }
        }

        private void 关于_Click(object sender, EventArgs e)
        {
            FrmHelper frmHelper = new FrmHelper();
            frmHelper.ShowDialog();
        }

        private void 隐藏主界面_Click(object sender, EventArgs e)
        {
            this.Visible = false;
        }

        private void 显示主界面_Click(object sender, EventArgs e)
        {
            //显示窗体
            this.Visible = true;
            //恢复窗体尺寸状态
            this.WindowState = FormWindowState.Normal;
        }

        private void 退出_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult dialogResult = new FrmMsgBoxWithAck("是否确定要退出系统", "退出系统").ShowDialog();
            if (dialogResult == DialogResult.OK)
            {
                //关闭存储定时器
                this.storeTimer.Stop();
                this.updateTimer.Stop();
                CommonMethods.listener.Stop();
                //关闭线程
                CommonMethods.IsExit = true;
                CommonMethods.plcDevice?.Cts?.Cancel();
                CommonMethods.PlcLink?.Disconnect();
                Thread.Sleep(500);
                notifyIcon1.Dispose();
                this.Dispose();//清理正在使用的资源     `在这里插入代码片`
                System.Environment.Exit(0);//退出全部线程  
                System.Diagnostics.Process.GetCurrentProcess().Kill();
            }
            else
            {
                e.Cancel = true;
            }
        }
        #endregion

        /// <summary>
        /// 获取鼠标光标的当前位置
        /// </summary>
        /// <param name="pt"></param>
        /// <returns></returns>
        [DllImport("user32.dll")]
        public static extern bool GetCursorPos(out Point pt);

        /// <summary>
        /// 刷卡用户登录超时检查
        /// </summary>
        /// <param name="secTime"></param>
        private void UserTimeOut(int secTime)
        {
            Task task = Task.Run(() =>
            {
                for (int i = 0; i < secTime; i++)
                {
                    GetCursorPos(out Point sourcePoint);
                    System.Threading.Thread.Sleep(1000);
                    GetCursorPos(out Point currentPoint);
                    if (sourcePoint.X != currentPoint.X | sourcePoint.Y == currentPoint.Y)
                    {
                        i = 0;
                    }
                    if (CommonMethods.LoginOut)
                    {
                        break;
                    }
                }
                LoginLocalOut();
            });
        }


        private void LoginLocalOut()
        {
            CommonMethods.AddOPLog(false, $"退出成功，退出用户：{CommonMethods.currentAdmin?.LoginName},权限：{CommonMethods.currentAdmin?.LoginLevel}");
            LoggerHelp.WriteLog($"用户：" + CommonMethods.currentAdmin?.LoginName + "-退出");
            CommonMethods.LoginOut = true;

        }

        #endregion

        /// <summary>
        /// 非刷卡模式
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 非刷卡模式ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmLogin frmLogin = new FrmLogin();
            if (frmLogin.ShowDialog() == DialogResult.OK)
            {

                CommonMethods.sysConfig.SwipeCardMode = false;
                IniConfigHelper.WriteIniData("配置信息", "开启刷卡模式", CommonMethods.sysConfig.SwipeCardMode.ToString());
                lbl_LoginLevel.Text = CommonMethods.currentAdmin?.LoginLevel;
                lbl_LoginName.Text = CommonMethods.currentAdmin?.LoginName;
                lbl_LoginName.Visible = true;
                //登录日志
                CommonMethods.AddOPLog(false, $"登录成功，登录用户：{CommonMethods.currentAdmin?.LoginName},权限：{CommonMethods.currentAdmin?.LoginLevel}");
            }
        }

        private void label8_Click(object sender, EventArgs e)
        {

        }

        private void btn_Return_Click(object sender, EventArgs e)
        {
            DialogResult dialogResult1 = new FrmMsgBoxWithAck("是否退出登录！", "提示").ShowDialog();
            if (dialogResult1 == DialogResult.OK)
            {
                this.lbl_LoginName.Text = "";
                this.lbl_LoginLevel.Text = "";
                CommonMethods.AddOPLog(false, $"退出登录成功，当前用户已注销");
                CommonMethods.IsLoginOk = false;
            }
        }
    }

    #region 消息筛选器
    internal class MessageFilter : IMessageFilter
    {
        //0x0200:鼠标移动
        //0x0202:鼠标左键UP
        //0x201:鼠标左键Down
        //0x0203:鼠标左键双击
        //0x0205:鼠标右键UP
        //0x0204:鼠标右键Down
        //0x020a:鼠标滚轮
        //0x100:键盘按下
        public bool PreFilterMessage(ref Message m)
        {
            //throw new NotImplementedException();
            if (m.Msg == 0x0200 || m.Msg == 0x0202 || m.Msg == 0x201 || m.Msg == 0x0203 || m.Msg == 0x0205 || m.Msg == 0x204 || m.Msg == 0x20a || m.Msg == 0x100)
            {
                CommonMethods.tickCount = 0;
                CommonMethods.tickHomeCount = 0;

            }
            return false;
        }
    }
    #endregion
}
